//自定义函数封闭作用域
(function(){
  
  var that ;

  function Game(map){
    //设置三个属性，存储食物、蛇、地图
    this.food = new Food();
    this.snake = new Snake();
    this.map = map;
    that = this;
  }

  //添加游戏开始的方法，初始化蛇和食物
  Game.prototype.start = function(){
    //1、添加蛇和食物到地图上
    this.food.render(this.map);
    this.food.render(this.map);
    this.food.render(this.map);
    this.snake.render(this.map);
    //游戏逻辑开始,让蛇运动
    //2.1 蛇自己运动
    runSnake();
    //2.2 通过上下左右控制方向
    
    bindKey();
  }

  //封装私有函数，控制上下左右的按键
  function bindKey(){
    document.onkeydown = function(e){
      //37~40 左上右下
      switch(e.keyCode){
        case 37:
          that.snake.direction = "left";
          break;
        case 38:
          that.snake.direction = "top";
          break;
        case 39:
          that.snake.direction = "right";
          break;
        case 40:
          that.snake.direction = "bottom";
          break;
      }
    }
  }

  function runSnake(){
    //开启定时器，让蛇运行起来
    var timer = setInterval(function(){
      //让蛇运动起来
      that.snake.move();
      //删除上次的蛇
      that.snake.remove(this.map);
      //渲染新的位置的蛇
      that.snake.render(this.map);

      //记录最大的位置
      var maxX = that.map.offsetWidth / that.snake.width;
      var maxY = that.map.offsetHeight / that.snake.height;
      //蛇头的位置
      var headX = that.snake.body[0].x;
      var headY = that.snake.body[0].y;

      //每一次蛇走到新的位置，都要判断一下是否吃到食物
      //2.3 判断蛇头与食物是否相撞，吃掉食物，让自己增加一节
      var foodX = that.food.x;
      var foodY = that.food.y;
      //获取蛇头的具体坐标位置
      var hX = headX * that.snake.width;
      var hY = headY * that.snake.height;
      //判断
      //对比数组中的每一个，谁被吃掉，删除自己，渲染新的元素
      for(var i = 0; i < that.food.elements.length; i++){
        if(that.food.elements[i].offsetLeft == hX && that.food.elements[i].offsetTop == hY){
          //吃到了食物
          that.food.remove(that.map, i);
          that.food.render(that.map);
          //添加一个新的蛇节
          var last = that.snake.body[that.snake.body.length-1];
          that.snake.body.push({
            x: last.x,
            y: last.y,
            color: last.color
          });
        }
      }
      //2.4 判断是否超出地图范围，结束游戏
      
      //进行判断
      if(headX < 0 || headX >=maxX || headY <= 0 || headY >= maxY){
        clearInterval(timer);
        alert("Game Over");
      }
    }, 100)
  }

  //将构造函数通过window暴露
  this.Game = Game;
 }
)();